<template>
  <div class="login">
    <div style="width: 100vw; height: 100vh; position: relative">
      <van-form @submit="onSubmit" class="home-login">
        <p style="text-align: center">在线商城平台</p>
        <van-cell-group inset>
          <van-field
            v-model="username"
            name="username"
            label="用户名"
            placeholder="请输入用户名"
            :rules="[{ required: iswarning, message: '请填写用户名' }]"
          />
          <van-field
            v-model="password"
            :type="iswarning ? 'password' : 'text'"
            name="password"
            label="密码"
            placeholder="请输入密码"
            :show-error="true"
            :right-icon="iswarning ? 'closed-eye' : 'eye-o'"
            @click-right-icon="iswarning = !iswarning"
            :rules="[{ required: true, message: '请填写密码' }]"
          />
        </van-cell-group>
        <div style="margin: 16px">
          <van-button round block type="primary" native-type="submit">
            登录
          </van-button>
          <van-button round block type="primary" native-type="submit">
            注册
          </van-button>
        </div>
      </van-form>
    </div>
  </div>
</template>
<script>
import router from "@/router";
import request from "@/utils/request";
import { showToast, showFailToast } from "vant";
export default {
  name: "login",
  data() {
    return {
      username: "python",
      password: "123456",
      // 控制图标的显示与隐藏
      iswarning: true,
    };
  },
  methods: {
    async onSubmit(values) {
      const reslult = await request.post(
        "/user/login?" +
          "username=" +
          this.username +
          "&" +
          "password=" +
          this.password +
          "&" +
          "rememberMe=" +
          true
      );
      if (reslult.data.code === "200") {
        showToast({
          message: "登录成功!",
          position: "top",
        });
        // 存储token和其他数据
        localStorage.setItem("token", reslult.data.token);
        localStorage.setItem("id", reslult.data.user.id);
        localStorage.setItem("username", reslult.data.user.username);
        localStorage.setItem("phonenumber", reslult.data.user.phonenumber);
        router.replace("/home");
      } else {
        showFailToast("用户名或密码错误");
      }
    },
  },
};
</script>
<style lang="scss">
.login {
  width: 100vw;
  height: 100vh;
  overflow: hidden;
  .home-login {
    width: 300px;
    height: 300px;
    margin: 200px auto;
  }
}
</style>
